package com.btpj.blog_server.service;

import com.btpj.blog_server.entity.Article;
import com.btpj.blog_server.entity.ViewCount;
import com.btpj.blog_server.mapper.ArticleMapper;
import com.btpj.blog_server.mapper.TagMapper;
import com.btpj.blog_server.mapper.ViewCountMapper;
import com.btpj.blog_server.utils.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class ArticleService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ArticleMapper articleMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    TagMapper tagMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ViewCountMapper viewCountMapper;

    /**
     * 获取用户下指定类型的文章列表
     *
     * @param state     指定类型
     * @param keywords  搜索匹配关键字
     * @param page      页数
     * @param pageCount 每页请求的数量
     * @return 文章列表
     */
    public List<Article> getAllArticlesByState(Integer state, String keywords, Integer page, Integer pageCount, boolean adminReq) {
        // 先判断用户是否是超级管理员，是的话置userId为null查询所有用户
        Long userId = UserManager.getCurrentUser().getId();
        int start = (page - 1) * pageCount;
        return articleMapper.getArticlesByState(state, adminReq ? null : userId, keywords, start, pageCount);
    }

    /**
     * 获取用户下指定类型的文章列表总数
     *
     * @param state    指定类型
     * @param keywords 搜索匹配关键字
     * @return 文章列表
     */
    public int getArticleCountByState(Integer state, String keywords, boolean adminReq) {
        // 先判断用户是否是超级管理员，是的话置userId为null查询所有用户
        Long userId = UserManager.getCurrentUser().getId();
        return articleMapper.getArticleCountByState(state, adminReq ? null : userId, keywords);
    }

    /**
     * 获取文章详情
     *
     * @param id 文章ID
     * @return 文章详情
     */
    public Article getArticleById(Long id) {
        // 在获取文章详情（阅读文章）时同时增加阅读次数
        articleMapper.updateArticleViewCount(id);
        return articleMapper.getArticleById(id);
    }

    /**
     * 删除指定ID的文章，多个
     *
     * @param articleIds 要删除的ID集合
     * @return 删除的指定ID的文章
     */
    public int deleteArticlesById(Long[] articleIds) {
        return articleMapper.deleteArticlesById(articleIds);
    }

    /**
     * 更改指定ID文章的状态
     *
     * @param articleIds 要更改状态的文章的ID集合
     * @param state      统一更改后的状态
     * @return 要更改状态的指定ID的文章
     */
    public int updateArticlesStatesById(Long[] articleIds, Integer state) {
        return articleMapper.updateArticlesStatesById(articleIds, state);
    }

    public int addArticle(Article article) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if (article.getState() == 1) {
            article.setPublishDate(timestamp);
        }
        article.setEditTime(timestamp);
        article.setUserId(UserManager.getCurrentUser().getId());
        article.setViewCount(0);

        int i = articleMapper.addArticle(article);
        String[] tagNames = article.getTagNames();
        if (tagNames != null && tagNames.length > 0) {
            int insertTagNum = addTagsToArticle(tagNames, article.getId());
            if (insertTagNum == -1) {
                return -1;
            }
        }
        return i;
    }

    public int updateArticle(Article article) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if (article.getState() == 1 && article.getPublishDate() == null) {
            article.setPublishDate(timestamp);
        }
        article.setEditTime(timestamp);

        int i = articleMapper.updateArticle(article);
        String[] tagNames = article.getTagNames();
        if (tagNames != null && tagNames.length > 0) {
            int insertTagNum = addTagsToArticle(tagNames, article.getId());
            if (insertTagNum == -1) {
                return -1;
            }
        } else {
            tagMapper.deleteTagsByArticleId(article.getId());
        }
        return i;
    }

    private int addTagsToArticle(String[] tagNames, Long articleId) {
        // 1.删除该文章目前所有的标签
        tagMapper.deleteTagsByArticleId(articleId);
        // 2.将上传上来的标签全部存入数据库
        tagMapper.saveTags(tagNames);
        // 3.查询这些标签的id
        List<Long> tagIds = tagMapper.getTagIdsByTagNames(tagNames);
        // 4.重新给文章设置标签
        int i = tagMapper.addTagsToArticle(tagIds, articleId);
        return i == tagNames.length ? i : -1;
    }

    public List<ViewCount> getViewCountsByUserId(Long userId) {
        return viewCountMapper.getViewCountsByUserId(userId);
    }

    public void viewCountPerDay() {
        viewCountMapper.viewCountPerDay();
    }
}
